package com.whc.interceptor;

import com.whc.constant.JwtClaimsConstant;
import com.whc.context.BaseContext;
import com.whc.properties.JwtProperties;
import com.whc.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 韦红材
 * @ClassName JwtTokenUserInterceptor
 * @data 2024/10/21 18:07
 * @Version V1.0
 **/
//@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是controller方法
        if(!(handler instanceof HandlerMethod)){
            //不是就返回
            return true;
        }
        String method=request.getMethod();
        if("GET".equals(method)){
            return true;
        }
        //从请求头里面获取token
        String token = request.getHeader(jwtProperties.getUserTokenName());
        if("upload".equals(token))return true;
        //校验令牌，并且获取埋入的id

     try{
         log.info("校验令牌");
         Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
         String userid = claims.get(JwtClaimsConstant.USER_ID).toString();
         log.info("当前用户的id:{}",userid);
         BaseContext.setCurrentId(Long.parseLong(userid));
         return true;
     }catch (Exception e){
        log.info("令牌校验失败");
         return false;
     }
    }

}
